<template>
    <div>
      <!-- 面包屑导航区 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区 -->
        <el-card>
              <el-row :gutter="10">
                <el-col :span="6">
                     <el-input 
                     placeholder="请输入内容" 
                     v-model="paramsInfo.query" 
                     class="input-with-select"
                      clearable
                      @clear="getUserList"
                     >
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6" >
                    <el-button type="primary" size="medium" @click="showDialog = true">添加用户</el-button>
                </el-col>
              </el-row>

              <!-- 表格区域 -->
         <el-table :data="userList"  border stripe>
            <el-table-column   type="index"  label="#"   width="80">  </el-table-column>
            <el-table-column  prop="username"  label="姓名"   width="180">  </el-table-column>
            <el-table-column  prop="email"  label="邮箱"   width="180">  </el-table-column>
            <el-table-column  prop="mobile"  label="电话"   width="180">  </el-table-column>
            <el-table-column  prop="role_name"  label="角色"   width="180">  </el-table-column>
            <el-table-column  label="状态"   width="180">  
                <template slot-scope="{row}">
                   <el-switch
                        v-model="row.mg_state"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        @change="changeSwitch(row)"
                        >
                   </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="{row}">
                    <el-button type="primary" size="small" icon="el-icon-edit" @click="editUser(row.id)"></el-button>
                    <el-button type="danger" size="small" icon="el-icon-delete" @click="delUser(row.id)"></el-button>
                     <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                        <el-button type="warning" size="small" icon="el-icon-setting" @click="fUser(row)"></el-button>
                     </el-tooltip>
                    
                </template>
            </el-table-column>
         </el-table>
          <!-- 分页功能 -->
           <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="paramsInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="paramsInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户是的对话框 -->
                    <el-dialog title="提示" :visible.sync="showDialog" width="50%" @close="closeDialog">
                        <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="80px">

                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="addForm.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="addForm.password"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="addForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="mobile">
                            <el-input v-model="addForm.mobile"></el-input>
                        </el-form-item>

                        </el-form>

                        <span slot="footer" class="dialog-footer">
                            <el-button @click="showDialog = false">取 消</el-button>
                            <el-button type="primary" @click="addUser">确 定</el-button>
                        </span>
                  </el-dialog>
                  <!-- 修改用户的对话框 -->
            
            <el-dialog
                title="修改用户信息"
                :visible.sync="dialogVisible"
                width="40%"
                @close ='editDialog'
                >
                <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editForm.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="editForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editQd">确 定</el-button>
                </span>
             </el-dialog>
            
            <!-- 分配角色对话框 -->
             <el-dialog
                title="分配角色"
                :visible.sync="userDialog"
                width="40%"
                @close ='kk'
                >
                 <div>
                    <p>当前的用户: {{userData.username}}</p> 
                    <p>当前的角色: {{userData.role_name}}</p>
                    <p>选择角色:
                        <el-select v-model="selectRole" placeholder="请选择">
                            <el-option
                                    v-for="item in rolesList"
                                    :key="item.id"
                                    :label="item.roleName"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </p>
                 </div>
                 
                <span slot="footer" class="dialog-footer">
                    <el-button @click="userDialog = false">取 消</el-button>
                    <el-button type="primary" @click="fRoleId">确 定</el-button>
                </span>
             </el-dialog>
    </div>
</template>

<script>
    export default {
          name:'userIndex',
         data () {
            return {
              paramsInfo:{
                 query:'',
                 pagenum:1,
                 pagesize:4
              },
              userList:[],
              total:0,
              showDialog:false,
              dialogVisible:false,
              addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
              },
              addFormRules:{
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
              
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
                   mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
              },
              editForm:{
                username:'',
                email:'',
                mobile:''
              },
              editFormRules:{
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
                   mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { min: 3, max: 9, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                   ],
              },
              userDialog:false,
              userData:{},
              rolesList:[],
              selectRole:[]
              }
         },
         created() {
             this.getUserList()
         },
         methods:{
           async  getUserList(){
            const {data:res} = await this.$http.get('users',{params:this.paramsInfo})
            this.userList = res.data.users
            this.total = res.data.total
             },

             handleSizeChange(val){
                 this.paramsInfo.pagesize = val
                 this.getUserList()
             },
             handleCurrentChange(val){
                 this.paramsInfo.pagenum = val
                 this.getUserList()
             },
           async  changeSwitch(row){
            const res =  await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
            if(res.meta.status !== 200) {
                this.$message.error('更新用户状态失败')
                row.mg_state = ! row.mg_state
            }else{
                this.$message.success('更新用户状态成功')
            }
             },
             //关闭对话框
             closeDialog(){
                this.$refs.addFormRef.resetFields()
             },
              addUser(){
                this.showDialog = false
                this.$refs.addFormRef.validate(async isOk => {
                    if(!isOk) return 
                   const {data:res} = await this.$http.post('/users',this.addForm)
                   if(res.meta.status !== 201) return this.$message.error('添加失败')
                   this.$message.success('添加用户成功')
                })
             },
           async editUser(id){
             const {data:res} = await this.$http.get('/users/' + id)
                this.editForm = res.data
                this.dialogVisible = true
             },
             editDialog(){
                this.$refs.editFormRef.resetFields()
             },
             editQd(){
                this.$refs.editFormRef.validate(async isOk => {
                     if(!isOk) return 
                     const {data:res} =    await this.$http.put('/users/' + this.editForm.id ,{
                            email:this.editForm.email,
                            mobile:this.editForm.mobile
                     })
                     if(res.meta.status !== 200){
                        return this.$message.error('修改信息有误')
                     }
                     this.dialogVisible = false
                     this.getUserList()
                     this.$message.success('更新数据成功')
                })
             },
           async delUser(id){
              const {data:res} =await this.$http.delete("users/" + id)
              if(res.meta.status !== 200) return this.$message.error('删除用户失败')
              this.$message.success('删除用户成功')
              this.getUserList()
             },
            //  分配角色
           async fUser(row){
                this.userData = row
               const {data:res} = await this.$http.get('/roles')
                if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
                this.rolesList = res.data
                //发送请求
             
                this.userDialog = true
            },
           async fRoleId(){
            const {data:res} = await this.$http.put(`users/${this.userData.id}/role`,{rid:this.selectRole})
               if(res.meta.status !== 200) return this.$message.error('分配角色失败')
               this.getUserList()
               this.userDialog = false
            },
            kk(){
                this.selectRole = ''
                this.userData = ''
            }
         }  
    }
</script>

<style lang="less" scoped>
   .el-breadcrumb{
    margin-bottom: 15px;
   }
   .el-table{
    margin-top: 15px;
    margin-bottom: 15px;
   }
</style>